#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from string import Template
from urllib2 import *
import urllib2
import simplejson
import datetime
import header
import footer

import About
import Contact
import Balazs
import Stalker
import Dump
import testPage
import Cleaner

from Functions import Functions
from Stalker import GeoTweet_model

#global variables, do not touch!
dbname = []
dbtweet = []

class MainHandler(webapp.RequestHandler):
 

 def queryDB(self):
  tweet_list = []
  t_database = db.GqlQuery("SELECT * FROM GeoTweet_model WHERE geo!= NULL LIMIT 40") # need to fix this somehow so  it orders them by the created at date.
  global dbname
  del dbname[:]
  global dbtweet
  del dbtweet[:]
  
  for each in t_database:
   temp = ""
   tweet = str(each.text.replace("\""," "))
   tweet = tweet.replace("\\"," ")
   tweet = tweet.replace("'"," ")
   name = str(each.screen_name.replace("\""," "))
   name = name.replace("'"," ")
   temp += "['NAME: " + name + " TWEET: " + tweet +"',"
   dbname.append(name)
   dbtweet.append(tweet)
   templatlng = each.geo
   templatlng = templatlng.replace("[","")
   templatlng = templatlng.replace("]","")
   templatlng = templatlng.split(",")
   temp += str(templatlng[0]) + "," + str(templatlng[1]) + ",'http://dl.dropbox.com/u/12563474/Icons/Google_Maps_Marker.png']" # This selects the marker type for tweets
   tweet_list.append(temp)
  
  
  #Inject Tweet Text Results
  url = "http://dl.dropbox.com/u/12563474/Icons/sight-2.png"
  ttx = Dump.Dump.getSilent()
  #self.response.out.write("DEBUG: "+str(len(ttx)))
  _i = 0
  _j = 1
  _k = 2
  ttx+=["COLLEGE STATION", "30.616800000000001", "-96.314599999999999"]
  for x in range(0,len(ttx),3):
    ttx[_i].replace("\"","")
    ttx[_i].replace("\'","")
    ttx[_i].replace("`","")
    ttx[_i].replace("\\","")
    ttx[_i].replace("'","")

    dbname.append(ttx[_i])
    dbtweet.append("Processed tweet result")
    
    temp_b = ""

    
    
    temp_b += "['Magic: " + ttx[_i] + "',"
    temp_b += str(ttx[_j]) + "," + str(ttx[_k]) +",'" +url +  "']"
#self.response.out.write("DEBUG 2: "+temp_b)
    tweet_list.append(temp_b)
    
    _i+=3
    _j+=3
    _k+=3  
    
  #inject deals
  url = "http://dl.dropbox.com/u/12563474/Icons/restaurant.png"
  deals = self.getDeals(30.624914,-96.338425,10,50)
  
  for each in deals:
   tempdeal = each[0] +" : " +each[1]
   tempdeal = tempdeal.replace("\"","")
   tempdeal = tempdeal.replace("\'","")
   tempdeal = tempdeal.replace("`","")
   tempdeal = tempdeal.replace("\\","")
   tempdeal = tempdeal.replace("'","")
   tempdeal = tempdeal.replace("\n","")
   tweet_list.append("['" + tempdeal +"',"+ str(each[2]) + "," + str(each[3]) +",'" +url +  "']")
   
  #inject deals2
  url = "http://dl.dropbox.com/u/12563474/Icons/restaurant2.png"
  deals2 = self.getDeals2()
  
  for each in deals2:
   tempdeal = each[0] +" : " +each[1]
   tempdeal = tempdeal.replace("\"","")
   tempdeal = tempdeal.replace("\'","")
   tempdeal = tempdeal.replace("`","")
   tempdeal = tempdeal.replace("\\","")
   tempdeal = tempdeal.replace("'","")
   tempdeal = tempdeal.replace("\n","")
   tweet_list.append("['" + tempdeal +"',"+ str(each[2]) + "," + str(each[3]) +",'" +url +  "']")
   
  return tweet_list
  
 #this function will return a table with names and tweets, it just needs to be inserted into the html
 def getTweetTable(self):
  table = ""
  for i in range(len(dbname)):
   table+="\
   <tr><td><font size=-2><b>" + dbname[i] + " </b></font></td></tr>\
   <tr><td><font size=-2>" + dbtweet[i]+"<br></font></td></tr>\
   <tr><td><hr width=100%></td></tr>"
  return table
  
  
 # this functions gets the tweets from the database, gets their titles, lats and lons and adds to map
 def getTweets(self):

  thisstring = "\nvar tweets = [\n"
  
  tweet_list = self.queryDB()
  
  for i in range(len(tweet_list)):
   if (len(tweet_list) - 1 == i):
    thisstring +=tweet_list[i] +"\n"
   else:
    thisstring +=tweet_list[i] + ",\n"
    
  thisstring += "];"
  return thisstring
  
 def getDeals2(self):
  url_deals_2 = 'http://www.findmespecials.com/api/search_specials?api_key=A3YdSK5GmGT1Ue4mUblV&version=2&lat=30.626502&lng=-96.33894&search_radius=10.0&page=1&search_type=now'
  
  try:
   f_deals_2 = urllib2.urlopen(url_deals_2)
   results = (f_deals_2.read()) #takes the output from the api call and loads it into a tractable list
  except urllib2.URLError, e:
   print(e.code)
   print(e.read())
   return
   
  #self.response.out.write(results)
  deals = []
  tempdeals = []
  results = results.split("\n")
  for each in results: #generates a list of places followed by the deal and the expiration of the deal
   deal_name = each.find('<name>')
   lat = each.find('<lat>')
   lng = each.find('<lng>')
   if (deal_name != -1 or lat != -1 or lng != -1):
    each = each.replace("<name>","").strip()
    each = each.replace("</name>","").strip()
    each = each.replace("<lat>","").strip()
    each = each.replace("</lat>","").strip()
    each = each.replace("<lng>","").strip()
    each = each.replace("</lng>","").strip()
    tempdeals.append(each)
    if( len(tempdeals) is 5):
     tempvar = tempdeals[1]
     tempdeals[1] = tempdeals[0]
     tempdeals[0] = tempvar
     tempdeals.pop()
     deals.append(tempdeals)
     tempdeals = []

  return deals
 
 def getDeals(self,x,y,radius=5,num_deals=5):#this function takes in a latitiude and longitude and radius
                   #then returns a list of num_deals, for restaurants, in the given radius, (radius<15mi is about as big as you should go) 
       
       #sample call for 50 deals in a 10 mile radius of College Station
       #getDeals(30.624914,-96.338425,10,50)
  lat = x
  lon = y
  rad = radius
  limit = num_deals #number of deals you want to have the API call return

  #this line builds the API call based on your input
  url = 'http://api.8coupons.com/v1/getdeals?key=69e32b0ed50c56affdfc86c76971581bf7d1dd31179d133310988798463d0a4df20ee1d9aa35d5b3fffdbd6fdeefdcca&lat='+str(lat)+'&lon='+str(lon)+'&mileradius='+str(rad)+'&limit='+str(limit)+'&categoryid=1'

  f = urllib2.urlopen(url)

  results = simplejson.loads(f.read()) #takes the output from the api call and loads it into a tractable list
  deals = []
  for each in results: #generates a list of places followed by the deal and the expiration of the deal
   temp_deals = []
   temp_deals.append(str(each['name']))
   temp_deals.append(str(each['dealTitle']))
   temp_deals.append(str(each['lat'])) 
   temp_deals.append(str(each['lon'])) 
   deals.append(temp_deals)
  return deals
 
 
 
 #Helper function to make life easier to create a map point
 def appendTweet(self, tweet, lat, lng, url_for_marker ,isFirst=True):
  if isFirst:
	  magic = "['"+str(tweet)+"',"+str(lat)+", "+str(lng)+ ",'" + str(url_for_marker)+ "'] "
  else:
	  magic = ",['"+str(tweet)+"',"+str(lat)+", "+str(lng)+ ",'" + str(url_for_marker)+ "'] "
  return magic
  
 def getMap(self):
  locationstring = "northgate+college+station,+tx" #Later can be modified to dynamic
  latlon = ""
  lat = ""
  lng = ""
  
  url_geocode_gmaps = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % (locationstring)     #google maps api to get lat,lon based on location
  f_geocode_gmaps = urlopen(url_geocode_gmaps)
  while not f_geocode_gmaps:
   f = urlopen(url_geocode_gmaps)
   print "bad"
  results = simplejson.loads(f_geocode_gmaps.read())
  #print results
  for each in results['results']:
   lat = str(each['geometry']['location']['lat'])
   lng = str(each['geometry']['location']['lng'])
   break
  
  head = """
   <script type="text/javascript">
    function initialize() {"""
    
  tweetvar = self.getTweets()
 
  

  #self.response.out.write("GREED "+tweetvar)
  
  #self.response.out.write(texttweetvar)
  
  latlng = " \nvar latlng = new google.maps.LatLng("+lat + "," + lng + ");"
  tail = latlng + """
    var myOptions = {
     zoom: 12,
     center: latlng,
     mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
    
    for (var i = 0; i < tweets.length; i++) {
     var beach = tweets[i];
     var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
     var image = beach[3]
     var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image,
      title: beach[0],
     });
    }

    }   
   </script>
   </head>
   <body onload="initialize()">
   <div class="main">
    <div class="header">
     <div class="header_resize">
      <div class="logo"></div>
      <div class="clr"></div>
     </div>
    </div>
    <div class="hbg">
     <div class="hbg_resize">
      <div class="menu_nav">
      <ul>
       <li><a href="index.html">Home</a></li>
       <li><a href="dump_db.html">Under the Hood</a></li>
       <li><a href="about.html">About the Project</a></li>
       <li><a href="contact.html">About Us</a></li>
      </ul>
      </div>
     </div>
    </div>
    <div class="content">
     <div class="content_resize">        
      <div class="left_sidebar">
      </div>
      <div class="mainbar">
       <div class="article">
        <h2><span>Our HootSpot Map</span></h2>
        <div class="clr"></div>
        <p><span class="date">"""+str(datetime.datetime.now())+"""
        </span> &nbsp;|&nbsp; Posted by <a href="#">Social Hootspot</a></p>
        <div id="map_canvas" style="width:600px; height:600px"></div>
       </div>
      </div>
      <div class="sidebar">
        <div class="gadget">
          <h2 class="star"><span>Tweets</span></h2>
          <div class="clr"></div>
				<ul class="sb_menu"><table width="250">"""+self.getTweetTable()+"""</table>
				</ul>
        </div>
        
      </div>
     </div>
    </div>
   </div>
  """
  return head + tweetvar + tail + footer.foot


 def get(self):
  self.response.out.write("""
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Project HootSpot</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <link href="stylesheets/main.css" rel="stylesheet" type="text/css" />
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
   <style type="text/css">
    html { height: 100% }
    body { height: 100%; margin: 0; padding: 0 }
   </style>
   <script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBf51SRNjnRRneaURosVSjdFHcGB2PCRaY&sensor=false">
   </script>""")
 # self.response.out.write(self.getTweetTable())
  self.response.out.write(self.getMap())
  #self.getDeals2()
  # <!--<script id='getbeezy_n2y0pjthCwy8_script' type='text/javascript' defer='defer' src='http://www.findmespecials.com/show_embedded_calendar?type=specials&type_id=109&count=5&city_id=10196&random_id=n2y0pjthCwy8'></script>-->


 

  #self.response.out.write(footer.foot)

def main():
    application = webapp.WSGIApplication([
  ('/', MainHandler),
  ('/index.html', MainHandler),
  ('/contact.html', Contact.Contact),
  ('/stalk.html', Stalker.Stalker),
  ('/dump_db.html', Dump.Dump),
  ('/balazs.html',Balazs.Balazs),
  ('/about.html', About.About),
  ('/cleaner.html', Cleaner.Cleaner),
  ('/test.html', testPage.testPage)
       
    ],
    
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
